<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useSettingsStore } from '../stores/modules/settings'
import { useAuthStore } from '../stores/modules/auth'
import Typewriter from 'typewriter-effect/dist/core'
import {
  createNewChat,
  getChatHistory,
  getChatMessages,
  sendMessage as sendChatMessage,
  deleteChat
} from '@/services/chatService'

// 基础状态管理
const message = ref('') // 当前输入的消息
const conversations = ref([]) // 所有对话列表
const currentChatId = ref(null) // 当前选中的对话ID
const loading = ref(false) // 加载状态
const settingsStore = useSettingsStore() // 设置状态管理
const authStore = useAuthStore() // 用户认证状态管理
const messageEndRef = ref(null) // 用于消息列表滚动定位

/**
 * 计算属性：获取当前会话的消息历史
 * 根据 currentChatId 筛选当前对话的消息
 */
const chatHistory = computed(() => {
  if (!currentChatId.value) return []
  const currentConversation = conversations.value.find((conv) => conv.id === currentChatId.value)
  return currentConversation ? currentConversation.messages || [] : []
})

/**
 * 平滑滚动到底部
 * @param {number} duration - 滚动动画持续时间(ms)
 */
const scrollToBottom = (duration = 300) => {
  const messagesContainer = document.querySelector('.chat-messages')
  if (!messagesContainer || !messageEndRef.value) return

  const targetScroll = messageEndRef.value.offsetTop
  const startScroll = messagesContainer.scrollTop
  const distance = targetScroll - startScroll
  const startTime = performance.now()

  // 缓动函数：平滑过渡
  const easeInOutQuad = (t) => {
    return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
  }

  // 动画帧
  const animate = (currentTime) => {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / duration, 1)
    messagesContainer.scrollTop = startScroll + distance * easeInOutQuad(progress)
    if (progress < 1) {
      requestAnimationFrame(animate)
    }
  }

  requestAnimationFrame(animate)
}

/**
 * 打字机效果实现
 * @param {HTMLElement} element - 目标DOM元素
 * @param {string} text - 要显示的文本内容
 */
const typeMessage = (element, text) => {
  if (!element || !text) return

  const typewriter = new Typewriter(element, {
    delay: 30, // 打字速度
    cursor: '' // 不显示光标
  })

  // 计算打字总时长
  const typingDuration = text.length * 30 // 每个字符30ms

  // 计算滚动次数和间隔
  const scrollIntervals = Math.max(Math.floor(typingDuration / 500), 1)
  const scrollInterval = typingDuration / scrollIntervals

  // 设置定时滚动
  let scrollCount = 0
  const scrollTimer = setInterval(() => {
    scrollToBottom(300)
    scrollCount++
    if (scrollCount >= scrollIntervals) {
      clearInterval(scrollTimer)
    }
  }, scrollInterval)

  // 开始打字效果
  typewriter
    .typeString(text)
    .callFunction(() => {
      clearInterval(scrollTimer)
      const messageEl = element.closest('.message-content')
      if (messageEl) {
        // 添加消息操作按钮（复制、重新生成）
        if (!messageEl.querySelector('.message-actions')) {
          // 创建操作按钮HTML
          const actionsHtml = `
            <div class="message-actions">
              <button class="action-btn copy-btn" title="复制">
                <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                </svg>
              </button>
              <button class="action-btn regenerate-btn" title="重新生成">
                <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
                  <path d="M21 2v6h-6"></path>
                  <path d="M3 12a9 9 0 0 1 15-6.7L21 8"></path>
                  <path d="M3 22v-6h6"></path>
                  <path d="M21 12a9 9 0 0 1-15 6.7L3 16"></path>
                </svg>
              </button>
            </div>
          `
          // 插入按钮并绑定事件
          messageEl.insertAdjacentHTML('beforeend', actionsHtml)
          const copyBtn = messageEl.querySelector('.copy-btn')
          const regenerateBtn = messageEl.querySelector('.regenerate-btn')

          if (copyBtn) {
            copyBtn.addEventListener('click', () => copyToClipboard(text))
          }
          if (regenerateBtn) {
            regenerateBtn.addEventListener('click', regenerateResponse)
          }
        }
      }
      // 最后滚动到底部确保显示完整
      scrollToBottom(300)
    })
    .start()
}

/**
 * 创建新对话
 * 生成临时ID并添加到对话列表
 */
const createNewConversation = async () => {
  const tempId = `temp_${Date.now()}`
  const newChat = {
    id: tempId,
    title: '新对话',
    displayTitle: '新对话',
    messages: [],
    isTemp: true // 标记为临时对话
  }

  conversations.value.unshift(newChat)
  currentChatId.value = tempId
  return tempId
}

/**
 * 更新对话标题
 * @param {Object} conversation - 对话对象
 * @param {string} userMessage - 用户消息内容
 */
const updateConversationTitle = (conversation, userMessage) => {
  if (!conversation) return

  // 对新对话，使用第一条用户消息作为标题
  if (conversation.displayTitle === '新对话' && userMessage) {
    const newTitle = userMessage.length > 15 ? userMessage.substring(0, 15) + '...' : userMessage
    conversation.displayTitle = newTitle
  }
}

/**
 * 切换当前对话
 * @param {string|number} chatId - 目标对话ID
 */
const switchConversation = async (chatId) => {
  if (currentChatId.value === chatId) return

  currentChatId.value = chatId

  // 查找目标对话
  const currentConversation = conversations.value.find((conv) => conv.id === chatId)

  // 如果对话存在但没有消息，则获取消息历史
  if (currentConversation && (!currentConversation.messages || currentConversation.messages.length === 0)) {
    try {
      const messages = await getChatMessages(chatId)
      if (Array.isArray(messages)) {
        // 为消息添加头像
        currentConversation.messages = messages.map((msg) => ({
          ...msg,
          avatar: msg.role === 'user'
            ? authStore.user?.avatar || 'https://api.dicebear.com/7.x/avataaars/svg?seed=user'
            : 'https://api.dicebear.com/7.x/bottts/svg?seed=AI'
        }))
      }
    } catch (error) {
      console.error(`获取会话 ${chatId} 的消息失败:`, error)
    }
  }

  // 切换后滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}

/**
 * 发送消息
 * 处理用户输入并获取AI响应
 */
const sendMessage = async () => {
  // 输入验证
  if (!message.value.trim()) return
  if (!authStore.isAuthenticated) {
    ElMessage.error('请先登录')
    return
  }

  console.log(settingsStore.sensitiveSettings.apiKey)
  if (!settingsStore.sensitiveSettings.apiKey) {
    ElMessage.warning('请先在设置中配置 API 密钥')
    return
  }

  const userMessage = message.value
  message.value = '' // 清空输入

  // 处理新对话创建
  let realChatId = currentChatId.value
  const isNewChat = !currentChatId.value ||
    conversations.value.find((c) => c.id === currentChatId.value)?.isTemp

  if (isNewChat) {
    try {
      // 创建新对话
      const response = await createNewChat(
        userMessage.length > 15 ? userMessage.substring(0, 15) + '...' : userMessage
      )

      if (response && response.success) {
        realChatId = response.data.chatId
        // 更新临时对话信息
        if (currentChatId.value) {
          const tempChat = conversations.value.find((c) => c.id === currentChatId.value)
          if (tempChat) {
            tempChat.id = realChatId
            tempChat.isTemp = false
            currentChatId.value = realChatId
          }
        } else {
          // 创建新对话记录
          const newChat = {
            id: realChatId,
            title: response.data.title,
            displayTitle: userMessage.length > 15 ? userMessage.substring(0, 15) + '...' : userMessage,
            messages: [],
            isTemp: false
          }
          conversations.value.unshift(newChat)
          currentChatId.value = realChatId
        }
      }
    } catch (error) {
      console.error('创建真实会话失败:', error)
      ElMessage.error('创建会话失败')
      return
    }
  }

  // 找到当前会话
  const currentConversation = conversations.value.find((conv) => conv.id === currentChatId.value)
  if (!currentConversation) {
    ElMessage.error('找不到当前会话')
    return
  }

  // 确保messages数组存在
  if (!currentConversation.messages) {
    currentConversation.messages = []
  }

  // 添加用户消息
  currentConversation.messages.push({
    role: 'user',
    content: userMessage,
    avatar: authStore.user?.avatar || 'https://api.dicebear.com/7.x/avataaars/svg?seed=user'
  })
  await nextTick()
  scrollToBottom()

  // 更新会话标题（首条消息时）
  updateConversationTitle(currentConversation, userMessage)

  // 添加AI消息占位（显示加载状态）
  const aiMessageIndex = currentConversation.messages.length
  currentConversation.messages.push({
    role: 'assistant',
    content: '',
    loading: true,
    avatar: 'https://api.dicebear.com/7.x/bottts/svg?seed=AI'
  })
  await nextTick()
  scrollToBottom()

  try {
    loading.value = true
    const response = await sendChatMessage({
      message: userMessage,
      chatId: realChatId,
      model: settingsStore.settings.model || 'deepseek-chat',
      temperature: settingsStore.settings.temperature || 0.7
    })

    console.log('API响应:', response)

    if (response.success && response.data) {
      // 获取AI回复内容
      const aiResponse = response.data.choices[0].message.content

      // 找到当前会话
      const currentConversation = conversations.value.find((conv) => conv.id === currentChatId.value)
      if (!currentConversation) {
        throw new Error('找不到当前会话')
      }

      // 移除loading状态的消息
      currentConversation.messages = currentConversation.messages.filter(msg => !msg.loading)

      // 添加新的AI消息
      const newMessage = {
        role: 'assistant',
        content: aiResponse,
        avatar: 'https://api.dicebear.com/7.x/bottts/svg?seed=AI'
      }
      currentConversation.messages.push(newMessage)

      // 强制更新视图
      await nextTick()

      // 应用打字机效果
      const messageElements = document.querySelectorAll('.message.assistant')
      const lastMessageEl = messageElements[messageElements.length - 1]?.querySelector('.message-content')

      if (lastMessageEl) {
        lastMessageEl.innerHTML = ''
        const typewriterContainer = document.createElement('div')
        typewriterContainer.className = 'typewriter-text'
        lastMessageEl.appendChild(typewriterContainer)
        typeMessage(typewriterContainer, aiResponse)
      }

      // 滚动到底部
      scrollToBottom()
    }
  } catch (error) {
    console.error('发送消息失败:', error)

    // 找到当前会话
    const currentConversation = conversations.value.find((conv) => conv.id === currentChatId.value)
    if (currentConversation) {
      // 移除loading消息
      currentConversation.messages = currentConversation.messages.filter(msg => !msg.loading)
    }

    ElMessage.error(error.response?.data?.message || '发送消息失败')
  } finally {
    loading.value = false
  }
}

// 获取历史聊天记录
const fetchChatHistory = async () => {
  try {
    const data = await getChatHistory()
    if (data && data.length > 0) {
      const filteredConversations = data.filter((conv) => {
        return conv.messages && Array.isArray(conv.messages) && conv.messages.length > 0
      })

      conversations.value = filteredConversations.map((conversation) => {
        const messages = Array.isArray(conversation.messages)
          ? conversation.messages.map((msg) => ({
              ...msg,
              avatar:
                msg.role === 'user'
                  ? authStore.user?.avatar || 'https://api.dicebear.com/7.x/avataaars/svg?seed=user'
                  : 'https://api.dicebear.com/7.x/bottts/svg?seed=AI'
            }))
          : []

        let title = conversation.title
        if (messages.length > 0) {
          const firstUserMsg = messages.find((msg) => msg.role === 'user')
          if (firstUserMsg && firstUserMsg.content) {
            title =
              firstUserMsg.content.length > 15
                ? firstUserMsg.content.substring(0, 15) + '...'
                : firstUserMsg.content
          }
        }

        return {
          ...conversation,
          messages,
          displayTitle: title
        }
      })

      if (conversations.value.length > 0 && !currentChatId.value) {
        currentChatId.value = conversations.value[0].id
      }
    }
  } catch (error) {
    console.error('获取聊天记录失败:', error)
  }
}

// 格式化时间函数
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return '未知时间'
    return date.toLocaleString('zh-CN')
  } catch (error) {
    console.error('日期格式化出错:', error, dateString)
    return '未知时间'
  }
}
// 删除对话
const deleteConversation = async (chatId, event) => {
  if (event) event.stopPropagation()

  try {
    const confirmDelete = await ElMessageBox.confirm(
      '确定要删除此对话吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'save-button',
        cancelButtonClass: 'cancel-button'
      }
    ).catch(() => false)

    if (!confirmDelete) return
    // 删除临时对话
    const tempChat = conversations.value.find((c) => c.id === chatId && c.isTemp)
    if (tempChat) {
      conversations.value = conversations.value.filter((c) => c.id !== chatId)
      if (currentChatId.value === chatId) {
        if (conversations.value.length > 0) {
          await switchConversation(conversations.value[0].id)
        } else {
          currentChatId.value = null
        }
      }
      ElMessage.success('删除成功')
      return
    }

    const response = await deleteChat(chatId)

    if (!response || !response.success) {
      throw new Error(`删除失败: ${response?.message || '未知错误'}`)
    }

    conversations.value = conversations.value.filter((c) => c.id !== chatId)
    if (currentChatId.value === chatId) {
      if (conversations.value.length > 0) {
        await switchConversation(conversations.value[0].id)
      } else {
        currentChatId.value = null
      }
    }

    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除会话失败:', error)
    ElMessage.error(`删除失败: ${error.message}`)
  }
}

// 复制文本到剪贴板
const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage({
      message: '已复制到剪贴板',
      type: 'success',
      duration: 1500
    });
  }).catch(err => {
    console.error('复制失败:', err);
    ElMessage.error('复制失败');
  });
};

// 重新生成响应
const regenerateResponse = async () => {
  // 检查是否存在聊天记录
  if (!chatHistory.value || chatHistory.value.length < 2) {
    ElMessage.warning('没有可重新生成的消息');
    return;
  }

  // 获取最后一个用户消息
  const lastUserMessageIndex = [...chatHistory.value].reverse().findIndex(msg => msg.role === 'user');
  if (lastUserMessageIndex === -1) {
    ElMessage.warning('找不到用户消息');
    return;
  }

  const lastUserMessage = chatHistory.value[chatHistory.value.length - 2 - lastUserMessageIndex];

  // 检查是否身份验证和API配置
  if (!authStore.isAuthenticated) {
    ElMessage.error('请先登录');
    return;
  }

  if (!settingsStore.settings.apiKey) {
    ElMessage.warning('请先在设置中配置 API 密钥');
    return;
  }

  // 找到当前会话
  const currentConversation = conversations.value.find(conv => conv.id === currentChatId.value);
  if (!currentConversation) {
    ElMessage.error('找不到当前会话');
    return;
  }

  // 删除最后一条AI消息
  currentConversation.messages.pop();

  // 添加新的加载消息
  currentConversation.messages.push({
    role: 'assistant',
    content: '',
    loading: true,
    avatar: 'https://api.dicebear.com/7.x/bottts/svg?seed=AI'
  });
  await nextTick()
  scrollToBottom()

  try {
    loading.value = true;

    const response = await sendChatMessage({
      message: lastUserMessage.content,
      chatId: currentChatId.value,
      model: settingsStore.settings.model || 'deepseek-chat',
      temperature: settingsStore.settings.temperature || 0.7,
      regenerate: true
    });

    if (response.success && response.data) {
      const aiResponse = response.data.choices[0].message.content;

      // 更新AI消息
      const aiMessageIndex = currentConversation.messages.length - 1;
      currentConversation.messages[aiMessageIndex] = {
        role: 'assistant',
        content: aiResponse,
        avatar: 'https://api.dicebear.com/7.x/bottts/svg?seed=AI',
        loading: false
      };

      // 应用打字机效果
      await nextTick();
      const messageElements = document.querySelectorAll('.message.assistant');
      const lastMessageEl = messageElements[messageElements.length - 1]?.querySelector('.message-content');

      if (lastMessageEl) {
        lastMessageEl.innerHTML = '';
        const typewriterContainer = document.createElement('div');
        typewriterContainer.className = 'typewriter-text';
        lastMessageEl.appendChild(typewriterContainer);
        typeMessage(typewriterContainer, aiResponse);

        // 确保在打字机效果开始后滚动
        scrollToBottom(100)

        // 打字机效果完成后再次滚动
        setTimeout(() => {
          scrollToBottom()
        }, aiResponse.length * 30 + 500)
      }
    }
  } catch (error) {
    console.error('重新生成消息失败:', error);

    // 找到当前会话
    const currentConversation = conversations.value.find((conv) => conv.id === currentChatId.value)
    if (currentConversation) {
      // 移除loading消息
      currentConversation.messages = currentConversation.messages.filter(msg => !msg.loading)
    }

    ElMessage.error(error.response?.data?.message || '重新生成失败');
  } finally {
    loading.value = false
    await nextTick()
    scrollToBottom()
  }
};

onMounted(async () => {
  // 先获取所有会话列表
  await fetchChatHistory()

  // 检查是否有从历史记录页面传来的chatId
  let selectedId = null // 修改为普通变量，不使用ref

  // 方法1：从localStorage获取
  const storedChatId = localStorage.getItem('selectedChatId')
  if (storedChatId) {
    selectedId = storedChatId // 直接赋值，不使用.value
    localStorage.removeItem('selectedChatId') // 使用后清除
  }

  // 方法2：从URL查询参数获取
  const urlParams = new URLSearchParams(window.location.search)
  const queryId = urlParams.get('id')
  if (queryId) {
    selectedId = queryId // 直接赋值
  }

  // 如果找到了指定的会话ID，切换到该会话
  if (selectedId) {
    // 验证这个会话是否存在

    // 确保ID类型匹配
    const targetId = typeof selectedId === 'string' ? parseInt(selectedId, 10) : selectedId
    const targetConversation = conversations.value.find((conv) => conv.id === targetId)

    if (targetConversation) {
      await switchConversation(targetId)
    } else {
      // 如果有会话列表，切换到第一个
      if (conversations.value.length > 0) {
        await switchConversation(conversations.value[0].id)
      }
    }
  } else if (conversations.value.length > 0) {
    // 没有指定会话时，默认使用第一个会话
    await switchConversation(conversations.value[0].id)
  }

  // 确保滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
})
</script>

<template>
  <div class="chat-container">
    <!-- 侧边栏：会话列表 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h3>对话列表</h3>
        <button class="new-chat-btn" @click="createNewConversation">
          <i class="el-icon-plus"></i> 新对话
        </button>
      </div>
      <div class="conversation-list">
        <div
          v-for="conv in conversations"
          :key="conv.id"
          :class="['conversation-item', { active: currentChatId === conv.id }]"
          @click="switchConversation(conv.id)"
        >
          <div class="conversation-title">{{ conv.displayTitle }}</div>
          <div class="conversation-time">{{ formatDate(conv.updated_at) }}</div>
          <!-- 删除按钮 -->
          <button
            class="delete-btn"
            @click.stop="deleteConversation(conv.id, $event)"
            title="删除对话"
          >
            <i class="el-icon-delete"></i>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              fill="currentColor"
              viewBox="0 0 16 16"
            >
              <path
                d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"
              />
              <path
                fill-rule="evenodd"
                d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"
              />
            </svg>
          </button>
        </div>
      </div>
    </div>

    <!-- 聊天主区域 -->
    <div class="chat-main">
      <div class="chat-messages">
        <!-- 初始欢迎消息 -->
        <div v-if="chatHistory.length === 0" class="welcome-message">
          <div class="welcome-logo">
            <img src="../assets/ai-chat-logo.svg" alt="AI Chat Logo" />
          </div>
          <h1 class="welcome-title">智能AI助手，为您服务！</h1>
          <p class="welcome-desc">
            您可以向我咨询各类问题，我能够帮助您编写代码、解答疑惑、提供创意和建议。快来和我聊天吧！
          </p>
        </div>

        <!-- 聊天历史 -->
        <div v-for="(msg, index) in chatHistory" :key="index" :class="['message', msg.role]">
          <div class="avatar">
            <img :src="msg.avatar" :alt="msg.role" />
          </div>
          <div class="message-content">
            <div v-if="msg.loading" class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
            <div v-else class="message-text">
              {{ msg.content }}
            </div>
            <!-- 静态消息已有的按钮会保留，打字机效果完成后会动态添加按钮 -->
            <div v-if="msg.role === 'assistant' && !msg.loading && !msg.typewriterActive" class="message-actions">
              <button class="action-btn copy-btn" @click="copyToClipboard(msg.content)" title="复制">
                <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                </svg>
              </button>
              <button
                v-if="index === chatHistory.length - 1"
                class="action-btn regenerate-btn"
                @click="regenerateResponse()"
                title="重新生成"
              >
                <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
                  <path d="M21 2v6h-6"></path>
                  <path d="M3 12a9 9 0 0 1 15-6.7L21 8"></path>
                  <path d="M3 22v-6h6"></path>
                  <path d="M21 12a9 9 0 0 1-15 6.7L3 16"></path>
                </svg>
              </button>
            </div>
          </div>
        </div>
        <div ref="messageEndRef"></div>
      </div>

      <div class="input-area">
        <div class="input-container">
          <textarea
            v-model="message"
            @keyup.enter.exact.prevent="sendMessage"
            placeholder="请输入您想咨询的问题..."
            rows="2"
            :disabled="loading"
          ></textarea>
          <button @click="sendMessage" :disabled="loading || !message.trim()">
            <span v-if="loading">发送中...</span>
            <span v-else>发送</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  height: 100%;
  display: flex;
  background-color: var(--el-bg-color);
}

/* 侧边栏样式 */
.sidebar {
  width: 250px;
  border-right: 1px solid var(--el-border-color-lighter);
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color);
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.new-chat-btn {
  background-color: #4d6bfe;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

.new-chat-btn:hover {
  background-color: #3d5be0;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.conversation-item {
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative; /* 添加相对定位，以便于放置删除按钮 */
}

.conversation-item:hover {
  background-color: var(--el-fill-color-light);
}

.conversation-item.active {
  background-color: var(--el-fill-color-light);
  border-left: 3px solid var(--el-color-primary);
}

.conversation-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

/* 聊天主区域 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

/* 欢迎信息样式 */
.welcome-message {
  margin: 40px auto;
  text-align: center;
  max-width: 600px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px;
  background-color: var(--el-bg-color-overlay);
  border-radius: 16px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.05);
}

.welcome-logo {
  width: 100px;
  height: 100px;
  margin-bottom: 24px;
}

.welcome-logo img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.welcome-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 16px;
  color: var(--el-text-color-primary);
  background: linear-gradient(135deg, #4d6bfe, #8364e8);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.welcome-desc {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  line-height: 1.6;
  margin-bottom: 20px;
  max-width: 480px;
}

.message {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  max-width: 80%;
}

.message.user {
  flex-direction: row-reverse;
  margin-left: auto;
  margin-right: 0;
}

.message.assistant {
  margin-right: auto;
  margin-left: 0;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  padding: 12px 16px;
  border-radius: 8px;
  line-height: 1.5;
  background-color: var(--el-fill-color-light);
  border: 1px solid var(--el-border-color-lighter);
  overflow: hidden;
  max-width: 90%;
  word-break: break-word;
}

.message.user .message-content {
  background-color: var(--el-fill-color-light);
}

.message.assistant .message-content {
  background-color: var(--el-fill-color-light);
}

/* 打字机效果 */
.typewriter-text {
  white-space: pre-wrap;
  word-break: break-word;
}

/* 打字指示器动画 */
.typing-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 20px;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  margin: 0 2px;
  background-color: var(--el-text-color-secondary);
  border-radius: 50%;
  display: inline-block;
  opacity: 0.4;
}

.typing-indicator span:nth-child(1) {
  animation: bounce 1s infinite;
}

.typing-indicator span:nth-child(2) {
  animation: bounce 1s infinite 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation: bounce 1s infinite 0.4s;
}

@keyframes bounce {
  0%,
  60%,
  100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-4px);
  }
}

.input-area {
  padding: 16px 20px;
  background-color: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-lighter);
}

.input-container {
  position: relative;
  display: flex;
  align-items: center;
  max-width: 900px;
  margin: 0 auto;
  background-color: var(--el-bg-color-overlay);
  border-radius: 24px;
  border: 1px solid var(--el-border-color-light);
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.input-container:focus-within {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 12px rgba(77, 107, 254, 0.1);
}

textarea {
  flex: 1;
  width: 100%;
  padding: 12px 20px;
  border: none;
  border-radius: 24px;
  background-color: transparent;
  color: var(--el-text-color-primary);
  resize: none;
  font-size: 14px;
  outline: none;
}

button {
  margin-right: 8px;
  padding: 8px 24px;
  border: none;
  border-radius: 24px;
  background-color: #4d6bfe;
  color: white;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  flex-shrink: 0;
}

button:hover:not(:disabled) {
  background-color: #3d5be0;
  box-shadow: 0 4px 8px rgba(77, 107, 254, 0.2);
}

button:disabled {
  background-color: var(--el-color-primary-light-5);
  cursor: not-allowed;
}

/* 删除按钮样式 */
.delete-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  background: transparent;
  border: none;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
  opacity: 0;
  transition:
    opacity 0.2s,
    color 0.2s,
    background-color 0.2s;
  border-radius: 4px;
  padding: 0;
  margin: 0;
}

.conversation-item:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  color: #f56c6c;
  background-color: rgba(245, 108, 108, 0.1);
  box-shadow: none;
}

.cancel-button,
.save-button {
  background: transparent;
  border: none;
  color: var(--el-button-save-text-color);
}

.cancel-button {
  color: var(--el-button-cancel-text-color);
}

.cancel-button:hover {
  background: var(--el-button-cancel-hover-color);
  color: var(--el-button-cancel-hover-text-color) !important;
}

.save-button:hover {
  background: var(--el-button-save-hover-color);
  color: var(--el-button-save-hover-text-color);
}

/* 消息文本容器 */
.message-text {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
}

/* 消息操作按钮容器 */
.message-actions {
  display: flex;
  gap: 8px;
  margin-top: 5px;
}

/* 操作按钮样式 */
.action-btn {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: transparent;
  border: none;
  color: var(--el-text-color-secondary);
  transition: all 0.2s;
  padding: 0;
}

.action-btn:hover {
  background-color: var(--el-fill-color-light);
  color: var(--el-color-primary);
}

.copy-btn:hover {
  color: var(--el-color-success);
}

.regenerate-btn:hover {
  color: var(--el-color-warning);
}

/* 输入区域重新生成按钮 */
.regenerate-control {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.regenerate-control-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  color: var(--el-text-color-regular);
  background-color: var(--el-fill-color-light);
  border: none;
  border-radius: 16px;
  padding: 6px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.regenerate-control-btn:hover {
  background-color: var(--el-fill-color);
  color: var(--el-color-primary);
}
</style>

<!-- 添加一个非作用域的样式块用于动态创建的元素 -->
<style>
/* 消息操作按钮容器 */
.message-actions {
  display: flex;
  gap: 8px;
  margin-top: 5px;
}

/* 操作按钮样式 */
.action-btn {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: transparent;
  border: none;
  color: var(--el-text-color-secondary);
  transition: all 0.2s;
  padding: 0;
}

.action-btn:hover {
  background-color: var(--el-fill-color-light);
  color: var(--el-color-primary);
}

.copy-btn:hover {
  color: var(--el-color-success);
}

.regenerate-btn:hover {
  color: var(--el-color-warning);
}
</style>
